package cn.itrip.auth.service;


import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import com.alibaba.fastjson.JSON;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service("tokenService")
public class TokenServiceImpl implements TokenService{

    @Resource
    private RedisAPI redisAPI;

    //客户端标识-USERCODE-USERID--CREATEDATE-RONDEM(六位)
    @Override
    public String generateToken(String userAgent, ItripUser itripUser) {
        StringBuilder str=new StringBuilder();
        str.append("token:");
        UserAgent agent=UserAgent.parseUserAgentString(userAgent);
        if(agent.getOperatingSystem().isMobileDevice()){
            str.append("MOBILE-");
        }else{
            str.append("PC-");
        }
        str.append(MD5.getMd5(itripUser.getUserCode(),32)+"-");
        str.append(itripUser.getId().toString()+"-");
        str.append(new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date())+"-");
        str.append(MD5.getMd5(userAgent,6));
        return str.toString();
    }

    //pc端  一般是两小时
    //手机端   长期保存回话
    @Override
    public void saveToken(String token, ItripUser itripUser) {
        if(token.startsWith("token:PC")){
            redisAPI.set(token,2*60*60, JSON.toJSONString(itripUser));
        }else{
            redisAPI.set(token, JSON.toJSONString(itripUser));
        }
    }

    @Override
    public boolean validate(String userAgent, String token) {
        if(!redisAPI.exist(token)){
            return false;
        }
        String agentMD5=token.split("-")[4];   //拆分token 获取agentMD5
        if(!agentMD5.equals(MD5.getMd5(userAgent,6))){
            return false;
        }
        return true;
    }

    @Override
    public void delete(String token) {
        redisAPI.delete(token);
    }

    private long protectedTime=30*60;
    private int delay=2*60;
    @Override
    public String reloadToken(String userAgent, String token) throws Exception {
        //验证token是否有效
        if(!redisAPI.exist(token)){
            throw  new Exception("token无效");
        }
        //能否置换
        Date startTime=new SimpleDateFormat("yyyyMMddHHmmsss").parse(token.split("-")[3]);
        long passTime= Calendar.getInstance().getTimeInMillis()-startTime.getTime();
        if(passTime<protectedTime){
            throw  new Exception("token置换保护期内，不能进行置换，剩余"+(protectedTime-passTime)/1000);
        }
        ItripUser user=JSON.parseObject(redisAPI.get(token),ItripUser.class);
        //进行置换
        String newToken = generateToken(userAgent,user);
        //延时过期
        redisAPI.set(token , delay ,JSON.toJSONString(user));
        //新的token加入值Redis
        this.saveToken(newToken,user);
        return newToken;
    }
}
